<template>
  <BasicDrawer
    :destroyOnClose="true"
    v-bind="$attrs"
    @register="registerDrawer"
    :showFooter="true"
    title="退款"
    width="680px"
    @ok="onSave"
    okText="保存"
    :maskClosable="false">
    <div style="font-weight: 500;font-size: 16px;color: #333333;padding: 8px 0;margin-bottom: 4px;">
      购买信息
    </div>

    <div
      style="background: #FFFFFF;box-shadow: 0 1px 6px 0 rgba(229,197,197,0.5);border-radius: 4px;padding: 12px;">
      <a-flex align="center" justify="space-between"
              style="background: #F9F9F9;box-shadow: inset 0 -1px 0 0 #FFF0F0;border-radius: 4px 4px 0 0;height: 56px;margin: -12px -12px 12px -12px;padding: 0 12px;">
        <span style="font-weight: 600;font-size: 18px;color: #C95E78;">{{ record.goodsName }}</span>
        <span style="font-weight: 600;font-size: 18px;color: #C95E78;">x{{ record.goodsQty }}</span>
      </a-flex>

      <a-flex>
        <div style="flex: 1">
          <div style="font-size: 14px;color: #6D414C;">卡项</div>
          <div style="font-size: 14px;color: #6D414C;margin-top: 8px;">{{
              record.cardConsumeName||'--'
            }}
          </div>

          <div v-if="quoteCardItem.cardType===100"
               style="font-weight: 400;font-size: 14px;color: #666666;">
            <span> {{ getProductDiscount(quoteCardItem) }}</span>
            <span>余额</span> <span>¥</span><span>{{
              (quoteCardItem.remainAmount || 0) + (quoteCardItem.remainBounsScore || 0)
            }}</span>
          </div>
        </div>

        <div style="flex: 1">
          <div style="font-size: 14px;color: #6D414C;">美容师</div>
          <div style="font-size: 14px;color: #6D414C;margin-top: 8px;">{{
              record.cashierName
            }}
          </div>
        </div>

        <div style="flex: 1;text-align: right;">
          <div
            style="font-weight: 400;font-size: 14px;color: #999999;text-decoration:line-through;">
            <span>零售价</span><span>{{ record.totalShoppingPrice }}</span>
          </div>


          <div style="margin-top:6px"><span style="font-size: 14px;color: #6D414C;;">折后价&nbsp;&nbsp;¥</span><span
            style="font-size: 20px;color: #6D414C;"> {{ record.totalTransactionPrice }}</span></div>

        </div>
      </a-flex>

      <div style="border-bottom:1px solid #D8D8D8;width: 100%;margin: 12px 0;"/>

      <div style="text-align: right;">
        <div><span style="font-size: 14px;color: #6D414C;">应付&nbsp;&nbsp;¥</span>
          <span style="font-weight: 500;font-size: 20px;color: #6D414C;"> {{
              record.totalTransactionPrice
            }}</span></div>
      </div>

    </div>


    <div style="font-weight: 500;font-size: 16px;color: #333333;padding: 8px 0;margin: 12px 0;">
      退款信息
    </div>

    <BasicForm @register="registerForm1">
      <template #returnGoodsQty="{ model, field }">
        <a-row :gutter="24" align="middle">
          <a-col :span="8">
            <a-input-number v-model:value="model[field]" :min="1"
              :max="record.goodsQty-record.returnGoodsQty"
              :precision="0"
              @update:value="updateQty"
              />
          </a-col>
          <a-col :span="16">
            （可退货数量：{{ record.goodsQty - record.returnGoodsQty }}）
          </a-col>
        </a-row>
      </template>

      <template #totalReturnPrice="{ model, field }">
        <a-row :gutter="24" align="middle">
          <a-col :span="24">
<!--            :max="record.totalTransactionPrice || 0"-->
            <a-input-number v-model:value="model[field]" :min="0"
              :max="9999999"
              :precision="2"/>
          </a-col>
        </a-row>
      </template>

      <template #payExtensionCode="{ model, field }">
        <div class="data-group">
          <div
            :class="['use', 'cell', model[field]===o.value ? 'active' : 'tacit']"
            v-for="o in cashPayCodes"
            :key="o.value"
            @click="model[field] = o.value"
          >{{ o.label }}
          </div>
        </div>
      </template>
    </BasicForm>
    <BackDetail @register="registerDetail1" />
  </BasicDrawer>

</template>

<script setup>
import {defineOptions, reactive, ref} from 'vue';

import {BasicDrawer, useDrawerInner, useDrawer} from '@/components/Drawer';

import {useMessage} from '@/hooks/web/useMessage';
import {BasicForm, useForm} from "@/components/Form";
import {cashPayCodes, refundList, refundList2} from "@/api/ds.js";
import {POST} from "@/api/http.js";
import {getUserInfo} from "@/utils/auth";
import {round} from "@/api/util.js";
import {getProductDiscount} from "@/views/member/util.js";

import BackDetail from "../member/back-detail.vue";

const [registerDetail1, { openDrawer: TDlDrawer }] = useDrawer();

defineOptions({name: 'OrderRefund2'});

const emit = defineEmits(['complete']);
const state = reactive({title: ''});

const orderHeader = ref([]);
const record = ref({});
const quoteCardItem = ref({});

const {createMessage} = useMessage();

const [registerForm1, form1] = useForm({
  labelWidth: 100,
  baseColProps: {span: 24, style: {paddingRight: '36px'}},

  schemas: [
    {
      label: '退货数量',
      field: 'returnGoodsQty',
      required: true,
      component: 'InputNumber',
      slot: 'returnGoodsQty',
    },

    {
      label: '退款类型',
      field: 'refundChannels',
      required: true,
      component: 'RadioGroup',
      componentProps: {
        options: [],
        onChange(e) {
          if (e.target.value === '1') {
            form1.setFieldsValue({
              payExtensionCode: null
            })
            
            form1.updateSchema({
              field: 'payExtensionCode',
              ifShow: false
            })
          } else {
            form1.updateSchema({
              field: 'payExtensionCode',
              ifShow: true
            })
          }
        }
      },
    },

    {
      label: '退款金额',
      field: 'totalReturnPrice',
      required: true,
      component: 'InputNumber',
      ifShow: ({model}) => {
        return !(model['refundChannels'] === '1' && record.value.extensionCode === 'times');
      },
      componentProps: {
        min: 0,
        precision: 2,
      },
      slot: 'totalReturnPrice',
    },

    {
      label: '退款方式',
      field: 'payExtensionCode',
      required: true,
      ifShow: ({model}) => {
        return !(model['refundChannels'] === '1' && record.value.extensionCode === 'times');
      },
      component: 'RadioGroup',
      slot: 'payExtensionCode',
    },
    {
      label: '退款原因',
      field: 'cancelCustom',
      required: true,
      component: 'InputTextArea',
      componentProps: {
        rows: 6,
        maxlength: 200,
        showCount: true,
      },
    },


  ],
  showActionButtonGroup: false,
});


const [registerDrawer, {closeDrawer}] =
  useDrawerInner(async ({
                          orderHeader: header,
                          record: item
                        }) => {
    orderHeader.value = header;
    record.value = item;

    await form1.resetFields();

      form1.setFieldsValue({
        totalReturnPrice: record.value?.totalTransactionPrice / item.goodsQty * (item.goodsQty - item.returnGoodsQty) || 0,
        returnGoodsQty: item.goodsQty - item.returnGoodsQty || 0,
      });

      const { memberCode } = orderHeader.value;

      let tempList = item.extensionCode === 'times' ? refundList : refundList2;

      if (item.goodsExtendedCode?.split(',')?.[0]) {
        const currentCard =
          (
            await POST('/card/getUserOneCardBenefitsInfo', {
              pageFlag: false,
              memberCode,
              cardNo: item.goodsExtendedCode?.split(',')?.[0],
            })
          )?.userCardPack ?? {};

        tempList =
          currentCard.upgradeFlag === 1 ? refundList2.filter((d) => d.value === '2') : tempList;
      }

     

    const {cardConsumeCode} = record.value;

    quoteCardItem.value = (await POST('/card/getUserOneCardBenefitsInfo', {
      pageFlag: false,
      memberCode,
      cardNo: cardConsumeCode,
    }))?.userCardPack ?? {};

    /**
     * 抵扣卡被退卡后的商品退款的处理：不允许退卡余额
     */

    if (quoteCardItem.value?.status === 4) {
      tempList = tempList.filter(d => d.value === '2')
    }

    form1.updateSchema([
        {
          field: 'refundChannels',
          componentProps: { options: tempList },
        },
      ]);

  });
console.log(record.value)

function updateQty(value) {
  const goodsQty = record.value?.goodsQty ?? 1
  let count = record.value?.goodsQty - record.value?.returnGoodsQty;
  count = count <= 0 ? 1 : count;
  form1.setFieldsValue({
    totalReturnPrice: round(record.value?.totalTransactionPrice / goodsQty * value),
  });
}
async function onSave() {
  const formData = form1.getFieldsValue();
  const {
    cancelCustom,
    payExtensionCode,
    returnGoodsQty,
    totalReturnPrice,
    refundChannels
  } = formData;

  const {
    itemGoodsType, extensionCode, goodsQty,
    goodsSn, goodsName, extensionId, storeCode, benefitsType
  } = record.value;

  const {
    employeeCode: cashierCode,
    realName: cashierName,
  } = (await getUserInfo())?.resultBean ?? {};

  const {masterOrderSn, memberCode} = orderHeader.value;
  const returnPrice = round(totalReturnPrice );

  const item = {
    payExtensionCode,
    itemGoodsType,
    extensionCode,
    goodsQty: returnGoodsQty,
    returnGoodsQty,
    returnPrice,
    totalReturnPrice: round(totalReturnPrice),
    isBack: 1,
    goodsSn,
    goodsName,
    extensionId,
    storeCode,
    benefitsType,
    refundChannels,
    cashierCode,
    cashierName
  };

  const data = {
    masterOrderSn, memberCode,
    cashierCode, cashierName, cancelCustom,
    source: '21', referer: 'PC端',
    orderItemBeanList: [item]
  };

  const res = await POST('/cashier/createTDShopOrders', data)
  createMessage.success('退款成功');
  TDlDrawer(true, { record: res });
  emit('complete')
  // closeDrawer();
}
</script>

<style lang="less" scoped>
.card {
  margin: 8px 0 46px;
  padding: 12px;

  .c-title {
    display: flex;
    flex-direction: row;
    align-items: center;
    column-gap: 8px;
    color: #091f3d;
    font-size: 15px;
    font-weight: 600;
  }

  .c-body {
    margin-top: 16px;

    .label {
      color: #acb4bf;
    }

    .value {
      color: #091f3d;
    }
  }
}
</style>


<style lang="less" scoped>

.data-group {
  display: flex;
  flex-flow: row wrap;
  align-items: center;
  cursor: pointer;
  gap: 8px 12px;

  .cell {
    padding: 4px 20px;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 400;
  }

  .tacit {
    border: 1px solid #e0e5ec;
    color: #091f3d;
  }

  .active {
    border: 1px solid @primary-color;
    background-color: @primary-color;
    color: #fff;
  }
}
</style>
